//
//  ZZLightLineSettingVC.m
//  ZZBlue
//
//  Created by evan on 2017/10/16.
//  Copyright © 2017年 stonesMonkey. All rights reserved.
//

#import "ZZLightLineSettingVC.h"
#import "ZZLightLineTool.h"
#import "ZZLightLineModel.h"
#import "ZZLightLineGroupModel.h"
#import "ZZView.h"
#import "ZZLightViewSettingCVCellModel.h"
#import "ZZLightViewSettingCollectionViewCell.h"

#define kZZLightLineSettingCollectionViewCellIdentifer @"ZZLightLineSettingCollectionViewCellIdentifer"

@interface ZZLightLineSettingVC ()<UICollectionViewDelegate,UICollectionViewDataSource>
// 名称
@property (weak, nonatomic) IBOutlet UILabel *nameLable;

@property (nonatomic ,strong) ZZLightLineModel *changeModel;
// 流星
@property (weak, nonatomic) IBOutlet UIButton *liuXingBtn;
// 叠加
@property (weak, nonatomic) IBOutlet UIButton *dieJiaBtn;
// 跳变
@property (weak, nonatomic) IBOutlet UIButton *tiaoBianBtn;
// 覆盖
@property (weak, nonatomic) IBOutlet UIButton *fugaiBtn;
// 间隔Btn
@property (weak, nonatomic) IBOutlet UIButton *jiangeBtn;
// 展示图
@property (weak, nonatomic) IBOutlet UIImageView *showImageView;
// 色板View
@property (weak, nonatomic) IBOutlet ZZView *touchView;

@property (weak, nonatomic) IBOutlet UIButton *selectColorBtn;
// 高度Height
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightConstraint;
// 删除选中颜色
@property (weak, nonatomic) IBOutlet UIButton *deleteColorBtn;
// 颜色按钮
@property (weak, nonatomic) IBOutlet UILabel *colorNumberLabel;
// 从头到尾
@property (weak, nonatomic) IBOutlet UIImageView *rightImage;

@property (weak, nonatomic) IBOutlet UIImageView *leftImage;

@property (weak, nonatomic) IBOutlet UIImageView *centerImage;
//
@property (weak, nonatomic) IBOutlet UISlider *tuoWeiSlider;
@property (weak, nonatomic) IBOutlet UISlider *zuheSlider;
@property (weak, nonatomic) IBOutlet UISlider *pinLvSlider;
@property (weak, nonatomic) IBOutlet UISlider *lightSlider;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UILabel *zuheLabel;

@property (weak, nonatomic) IBOutlet UIView *selectStyleView;

// CollectionView 数据
@property (nonatomic, strong)ZZLightViewSettingCVCellModel *currentSelectModel;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flow;


@property (nonatomic, strong)NSMutableArray<NSMutableArray<ZZLightViewSettingCVCellModel *> *> *collectionViewModelGroup;
@property (nonatomic, strong)NSMutableArray<ZZLightViewSettingCVCellModel *> *collectionViewModels;

// 选择的Tag
@property (nonatomic ,assign) NSInteger selectBtnTag;
// 组合中的Tag
@property (nonatomic ,assign) NSInteger fuGaiSelectBtnTag;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tuoWeiLeng;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *zuheConstraints;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pinLvConstraints;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lightConstraint;

// 按钮
@property (weak, nonatomic) IBOutlet UIButton *ABtn;
@property (weak, nonatomic) IBOutlet UIButton *BBtn;
@property (weak, nonatomic) IBOutlet UIButton *CBtn;
@property (weak, nonatomic) IBOutlet UIButton *DBtn;
@property (weak, nonatomic) IBOutlet UIButton *EBtn;

@property (weak, nonatomic) IBOutlet UILabel *tuoweiLengthLabel;



@end

@implementation ZZLightLineSettingVC

- (void)viewDidLoad {
    [super viewDidLoad];

    UILabel *label = [UILabel new];
    label.font = [UIFont systemFontOfSize:17];
    label.text = NSLocalizedString(@"LIGHT_CELL_StyleTitle", nil);
    label.textColor = [UIColor whiteColor];
    label.frame = CGRectMake(0, 0, 100, 44);
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = label;

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"icon_fanh"] forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, 0, 32, 32);
    [btn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchDown];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];


    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(0, 0, 32, 32);
    saveBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [saveBtn setTitle:NSLocalizedString(@"LIGHT_CELL_Save",nil) forState:UIControlStateNormal];
    [saveBtn setTitleColor:[UIColor zColorWithRed:248 green:204 blue:40] forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchDown];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveBtn];

    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"ZZLightViewSettingCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:kZZLightLineSettingCollectionViewCellIdentifer];
    self.collectionView.backgroundColor = [UIColor blackColor];
    self.flow.itemSize = CGSizeMake(60, 45);
    self.flow.minimumInteritemSpacing = 4;
    
    [self setupSubView];

//    self.showView.layer.cornerRadius = 117 / 2.0;
//    self.showView.layer.masksToBounds = YES;
//
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(btn2Move:)];
    [self.selectColorBtn addGestureRecognizer:pan];
//
    self.fuGaiSelectBtnTag = 3001;


}

- (void)viewDidAppear:(BOOL)animated {

    [super viewDidAppear:animated];
     [self.scrollView setContentSize:CGSizeMake(Z_SCREEN_WIDTH, 1400)];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

#pragma mark - Func
- (void)setupSubView {

    // 添加点击事件
    [self setImageGestuper];

    // 设置slider
    [self setSlider];
    
    // 设置中间那个点
    self.selectColorBtn.frame = CGRectMake(60, 60, 30, 30);
    self.selectColorBtn.layer.cornerRadius = 15;
    self.selectColorBtn.layer.masksToBounds = YES;
    self.selectColorBtn.layer.borderWidth = 3;
    self.selectColorBtn.layer.borderColor = [UIColor whiteColor].CGColor;

    // 设置中间View点击
    [self setTouView];
    // 设置删除Btn
    [self setDeleteBtn];
}

- (void)setTouView {
    
    self.touchView.viewDidClick = ^(UIColor *color, CGPoint location) {
        
        if (self.currentSelectModel == nil) {
            
            return ;
        }
        
        self.currentSelectModel.color = color;
        
        if (self.selectBtnTag == 1004) {
            
            NSInteger index = [self.collectionViewModelGroup[self.fuGaiSelectBtnTag - 3001] indexOfObject:self.currentSelectModel];
            ZZColorRGBA *rgba = [self.changeModel.colorsGroup[self.fuGaiSelectBtnTag - 3001] objectAtIndex:index];
            NSArray *rgbaArr =[ZZCircleTool colorForGGB:color];
            rgba.R = [rgbaArr[0] floatValue];
            rgba.G = [rgbaArr[1] floatValue];
            rgba.B = [rgbaArr[2] floatValue];
            
        } else {
            
            NSInteger index = [self.collectionViewModels indexOfObject:self.currentSelectModel];
            ZZColorRGBA *rgba = self.changeModel.colors[index];
            NSArray *rgbaArr =[ZZCircleTool colorForGGB:color];
            rgba.R = [rgbaArr[0] floatValue];
            rgba.G = [rgbaArr[1] floatValue];
            rgba.B = [rgbaArr[2] floatValue];
            
        }
        
        [self changeBtn:self.selectBtnTag];
        self.selectColorBtn.center = location;
        [self.collectionView reloadData];
    };
}

- (void)setDeleteBtn {
    
    self.deleteColorBtn.layer.cornerRadius = 12.5;
    self.deleteColorBtn.layer.borderWidth = 1;
    self.deleteColorBtn.layer.borderColor = [UIColor zColorWithRed:102 green:102 blue:102].CGColor;
    self.deleteColorBtn.layer.masksToBounds = YES;
}

- (void)setImageGestuper {

    self.leftImage.userInteractionEnabled = YES;
    self.rightImage.userInteractionEnabled = YES;
    self.centerImage.userInteractionEnabled = YES;

    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectDictForType:)];
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectDictForType:)];
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectDictForType:)];
    [self.rightImage addGestureRecognizer:tap1];
    [self.leftImage addGestureRecognizer:tap2];
    [self.centerImage addGestureRecognizer:tap3];
}

- (void)setSlider {

    [self setSliderView:self.tuoWeiSlider];
    [self.tuoWeiSlider addTarget:self action:@selector(tuoweiSliderChange) forControlEvents:UIControlEventValueChanged];
    [self setSliderView:self.zuheSlider];
    [self.zuheSlider addTarget:self action:@selector(colorZuHeSliderChange) forControlEvents:UIControlEventValueChanged];
    [self setSliderView:self.pinLvSlider];
    [self.pinLvSlider addTarget:self action:@selector(pinLvSliderChange) forControlEvents:UIControlEventValueChanged];
    [self setSliderView:self.lightSlider];
    [self.lightSlider addTarget:self action:@selector(lightValueSliderChange) forControlEvents:UIControlEventValueChanged];
}

- (void)setSliderView:(UISlider *)slider {

    slider.backgroundColor = [UIColor zColorWithHex:0x34373b];
    slider.minimumTrackTintColor =  [UIColor zColorWithHex:0x34373b];
    slider.maximumTrackTintColor =  [UIColor zColorWithHex:0x34373b];
    slider.layer.cornerRadius = 8;
    [slider setThumbImage:[UIImage imageNamed:@"icon_huaik"] forState:UIControlStateNormal];
}


- (UIColor *)colorOfPoint:(CGPoint)point {
    unsigned char pixel[4] = {0};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
    
    CGContextTranslateCTM(context, -point.x, -point.y);
    
    [self.touchView.layer renderInContext:context];
    
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    
    UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0];
    
    return color;
}

#pragma mark - action

- (IBAction)changeName:(UIButton *)sender {
    
    self.fuGaiSelectBtnTag = sender.tag;
    self.currentSelectModel.isSelect = NO;
    self.currentSelectModel = nil;
    [self.ABtn setSelected:NO];
    [self.BBtn setSelected:NO];
    [self.CBtn setSelected:NO];
    [self.DBtn setSelected:NO];
    [self.EBtn setSelected:NO];
    [sender setSelected:YES];
    
    self.ABtn.layer.borderColor = [UIColor clearColor].CGColor;
    self.BBtn.layer.borderColor = [UIColor clearColor].CGColor;
    self.CBtn.layer.borderColor = [UIColor clearColor].CGColor;
    self.DBtn.layer.borderColor = [UIColor clearColor].CGColor;
    self.EBtn.layer.borderColor = [UIColor clearColor].CGColor;
    
    sender.layer.cornerRadius = 16.5;
    sender.layer.borderWidth = 2;
    sender.layer.borderColor = [UIColor redColor].CGColor;
    
    
    [self changeBtn:self.selectBtnTag];
}


- (void)tuoweiSliderChange {

    int length = 0;
    if (self.tuoWeiSlider.value == 1.0) {
        
        length = 9;
    } else {
        
        length = (int)(self.tuoWeiSlider.value * 10) % 10;
    }
    
    self.changeModel.tuoWeiLength = length / 10.0;
    self.tuoweiLengthLabel.text = [NSString stringWithFormat:@"当前拖动长度:%d",length];
    [self changeBtn:self.selectBtnTag];
}

- (void)colorZuHeSliderChange {

    self.currentSelectModel.isSelect = NO;
    self.currentSelectModel = nil;
    if (self.fuGaiSelectBtnTag - 3000 >= self.zuheSlider.value * 10 / 2) {
        
        self.zuheSlider.value = (self.fuGaiSelectBtnTag - 3000) * 0.2;
        return;
    }
    
    NSLog(@"colorZuHeSliderChange: %lf",self.zuheSlider.value * 10);
    
    int count = self.zuheSlider.value * 10 / 2;
    if (count < 1) {
        
        count = 1;
    }
    self.changeModel.colorZuHeShu = count;
    self.zuheLabel.text = [NSString stringWithFormat:@"%@ %d",NSLocalizedString(@"LIGHT_LightZuhe", nil),count];
    self.changeModel.colors = [NSMutableArray arrayWithArray:self.changeModel.colorsGroup[0]];
    NSInteger modelsCount = self.changeModel.colorsGroup.count;
    if (modelsCount > count) {
        
        for (NSInteger index = 0; index < modelsCount - count; index++) {
            
            [self.changeModel.colorsGroup removeLastObject];
            [self.collectionViewModelGroup removeLastObject];
        }
    } else if (modelsCount < count) {
        
        for (NSInteger index = 0; index < count - modelsCount; index++) {
            
            
            NSMutableArray *arr = self.changeModel.colorsGroup[0];
            NSMutableArray *newMtbArr = [NSMutableArray array];
            for (ZZColorRGBA *rgba in arr) {
                
                [newMtbArr addObject:[rgba copy]];
            }
            [self.changeModel.colorsGroup addObject:[NSMutableArray arrayWithArray:newMtbArr]];
            
            [newMtbArr removeAllObjects];
            for (ZZLightViewSettingCVCellModel *model in self.collectionViewModelGroup[0]) {
                
                [newMtbArr addObject:[model copy]];
            }
            [self.collectionViewModelGroup addObject:[NSMutableArray arrayWithArray:newMtbArr]];
        }
    }
    
    for (UIView *view in  self.selectStyleView.subviews) {
        
        view.hidden =YES;
    }
    
    for (NSInteger index = 0; index < count; index++) {
        
        [self.selectStyleView viewWithTag:index + 3001].hidden = NO;
    }
    
    [self.collectionView reloadData];
}

- (void)pinLvSliderChange {
    
    NSLog(@"tuoweiSliderChange: %lf",self.pinLvSlider.value);
    self.changeModel.pinLv = self.pinLvSlider.value;
}

- (void)lightValueSliderChange {
    
    self.changeModel.lightValue = self.lightSlider.value;
    NSLog(@"tuoweiSliderChange: %lf",self.lightSlider.value);
}

- (void)selectDictForType:(UITapGestureRecognizer *)tap {

     NSInteger type = tap.view.tag -1 ;
    if (type == self.changeModel.dicrection) {
        
        return;
    }
    switch (type) {
        case LightLineDirectionRight:
        {
            
            self.changeModel.dicrection = LightLineDirectionRight;
        }

            break;
        case LightLineDirectionLeft:
        {
             self.changeModel.dicrection = LightLineDirectionLeft;
        }
            break;
            case LightLineDirectionCenter:
        {
             self.changeModel.dicrection = LightLineDirectionCenter;
        }
            break;
        default:
            break;
    }
    
    [self changeBtn:self.selectBtnTag];
}

- (void)btn2Move:(UIPanGestureRecognizer *)pan {
    
    CGPoint  point = [pan translationInView:self.touchView];
    CGFloat width = self.touchView.width - self.selectColorBtn.width / 2;
    
    CGRect originalFrame = self.selectColorBtn.frame;
    
    originalFrame.origin.x += point.x;
    originalFrame.origin.y += point.y;
    
    // 圆心
    CGPoint center = CGPointMake(CGRectGetMidX(originalFrame) - width / 2,CGRectGetMidY(originalFrame) - width /2);
    
    CGFloat offetX  = self.selectColorBtn.width / 2;
    CGFloat offerY = self.selectColorBtn.height / 2;
    if (center.x > 0) {
        
        offetX = offetX / 2;
    }
    if(center.y > 0) {
        
        offerY = offerY / 2;
    }
    
    CGFloat x2 = fabs(center.x - offetX ) * fabs(center.x - offetX);
    CGFloat y2 = fabs(center.y - offerY)  * fabs(center.y  - offerY) ;
    CGFloat length = sqrt(x2 + y2);
    if (length >= width / 2) {
        
        originalFrame = self.selectColorBtn.frame;
    }
    
    self.selectColorBtn.frame = originalFrame;
    [pan setTranslation:CGPointZero inView:self.touchView];
    
    switch (pan.state) {
        case UIGestureRecognizerStateChanged:
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateFailed:
        case UIGestureRecognizerStateCancelled:
        {
            // 输出当前ImageView上的颜色值
            UIColor*color = [self colorOfPoint:self.selectColorBtn.center];
            
            if (self.currentSelectModel) {
                
                self.currentSelectModel.color = color;
                [self.collectionView reloadData];
                if (self.selectBtnTag == 1004) {
                    
                    NSInteger index = [self.collectionViewModelGroup[self.fuGaiSelectBtnTag - 3001] indexOfObject:self.currentSelectModel];
                    
                    ZZColorRGBA *rgba = self.changeModel.colorsGroup[self.fuGaiSelectBtnTag - 3001][index];
                    NSArray *rgbaArr =[ZZCircleTool colorForGGB:color];
                    rgba.R = [rgbaArr[0] floatValue];
                    rgba.G = [rgbaArr[1] floatValue];
                    rgba.B = [rgbaArr[2] floatValue];
                } else {
                    
                    NSInteger index = [self.collectionViewModels indexOfObject:self.currentSelectModel];
                    ZZColorRGBA *rgba = self.changeModel.colors[index];
                    NSArray *rgbaArr =[ZZCircleTool colorForGGB:color];
                    rgba.R = [rgbaArr[0] floatValue];
                    rgba.G = [rgbaArr[1] floatValue];
                    rgba.B = [rgbaArr[2] floatValue];
                }
                
                // 改变index颜色
                [self changeBtn:self.selectBtnTag];
            }
#pragma mark - 颜色输出
            NSLog(@"%@",color);
        }
            break;
            
        default:
            break;
    }
}

- (IBAction)changeModelBtnClick:(UIButton *)sender {

    self.currentSelectModel.isSelect = NO;
    self.currentSelectModel = nil;
    
    [self changeBtn:sender.tag];
}

#pragma mark - 改变按钮样式
- (void)changeBtn:(NSInteger )tag {

    self.selectBtnTag = tag;

    
    self.liuXingBtn.selected = NO;
    self.dieJiaBtn.selected = NO;
    self.tiaoBianBtn.selected = NO;
    self.fugaiBtn.selected = NO;
    self.jiangeBtn.selected = NO;
    self.changeModel.model = tag;
    if (self.selectBtnTag == 1004 ) {

        [self.changeModel reloadImageForIndex:self.fuGaiSelectBtnTag - 3001];
    } else {

        [self.changeModel reloadImage];
    }

    NSString *path_document = NSHomeDirectory();
    NSString *imagePath = [path_document stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@",self.changeModel.imagePath]];

    self.showImageView.image = [UIImage imageWithContentsOfFile:imagePath];
    NSLog(@"%@",imagePath);

    self.tuoWeiLeng.constant = 100;
    self.pinLvConstraints.constant = 100;
    self.zuheConstraints.constant = 100;
    self.lightConstraint.constant = 100;

    self.colorNumberLabel.text = [NSString stringWithFormat:@"%ld", [self.collectionViewModels count]];

    switch (tag) {
        case 1001:
        {
            self.liuXingBtn.selected = YES;
            self.zuheConstraints.constant = 0;
            self.heightConstraint.constant = 45;
            [self.view layoutIfNeeded];
#pragma mark -第一种模式（七彩）依此类推
        }
            break;
        case 1002:
        {
            self.dieJiaBtn.selected = YES;

            self.zuheConstraints.constant = 0;
            self.heightConstraint.constant = 45;
            [self.view layoutIfNeeded];
        }
            break;
        case 1003:
        {
            self.tiaoBianBtn.selected = YES;
            self.heightConstraint.constant = 45;
            self.tuoWeiLeng.constant = 0;
            [self.view layoutIfNeeded];

        }
            break;
        case 1004:
        {
            self.fugaiBtn.selected = YES;
            self.tuoWeiLeng.constant = 0;
            self.heightConstraint.constant = 98;
            [self.view layoutIfNeeded];

            self.colorNumberLabel.text = [NSString stringWithFormat:@"%ld", [self.collectionViewModelGroup[0] count]];

        }
            break;
        case 1005:
        {
            self.jiangeBtn.selected = YES;
            self.tuoWeiLeng.constant = 0;
            self.zuheConstraints.constant = 0;
            self.heightConstraint.constant = 45;
            [self.view layoutIfNeeded];

        }
            break;

        default:
            return;
            break;
    }



    //    NSMutableArray *colors = [NSMutableArray array];
    //    if (self.changeModel.colors.count > 0) {
    //
    //        for (ZZColorRGBA *rgba in self.changeModel.colors) {
    //
    //            [colors addObject: [rgba color]];
    //        }
    //    }

    [self.collectionView reloadData];
}

- (void)back {

    if ([self.model isEqualModel:self.changeModel]) {
        
        
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                       message:@"尚未保存修改，你需要保存？"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"不保存" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                                  [self.navigationController popViewControllerAnimated:YES];
                                                              }];
        
        [alert addAction:defaultAction];
        
        UIAlertAction* sureAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction * action) {
                                                               
                                                               [self.model equalToModel:self.changeModel];
                                                               // 保存并推出
                                                               if(self.updateData) {
                                                                   
                                                                   self.updateData(self.model,self.isAddCustomer);
                                                               }
                                                               
                                                               [self.navigationController popViewControllerAnimated:YES];
                                                           }];
        
        [alert addAction:sureAction];
        [self presentViewController:alert animated:YES completion:nil];
        
        
        
    }
}

- (IBAction)changeNameBtnClick:(UIButton *)sender {


    UIAlertController* alertVc = [UIAlertController alertControllerWithTitle:@"修改名称"
                                                                     message:nil
                                                              preferredStyle:UIAlertControllerStyleAlert];

    __block UITextField *nameTextFIeld = nil;
    [alertVc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {

        nameTextFIeld = textField;
    }];



    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                          handler:^(UIAlertAction * action) {}];

    UIAlertAction* sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action) {

                                                           if (nameTextFIeld.text.length == 0) {

                                                               return ;
                                                           }
                                                           self.nameLable.text = nameTextFIeld.text;
                                                           self.changeModel.title = nameTextFIeld.text;
                                                       }];
    [alertVc addAction:defaultAction];
    [alertVc addAction:sureAction];
    [self presentViewController:alertVc animated:YES completion:nil];
}


- (void)saveBtnClick {

    if(self.model.model == ZZLightViewSettingCVCellStyleAdd) {
        
        if(self.updateData) {
            
            self.updateData(self.model,self.isAddCustomer);
        }
        return;
    }
    
    if ([self.model isEqualModel:self.changeModel]) {
        
        
        NSLog(@"什么都不用做");
    } else {
        
        [self.model equalToModel:self.changeModel];
        // 保存并推出
        if(self.updateData) {
            
            self.updateData(self.model,self.isAddCustomer);
        }
        
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)deletaBtnClick:(UIButton *)sender {
    
    if (((self.collectionViewModels.count >1 || [self.collectionViewModelGroup[0] count] > 1) )&& self.currentSelectModel.isSelect == YES) {
        
        if (self.selectBtnTag == 1004) {
            
            NSUInteger index = [self.collectionViewModelGroup[self.fuGaiSelectBtnTag - 3001] indexOfObject:self.currentSelectModel];
            for (NSInteger i = 0; i < self.changeModel.colorsGroup.count; i++) {
                
                [self.changeModel.colorsGroup[i] removeObjectAtIndex:index];
            }
            
            for (NSInteger i = 0; i < self.collectionViewModelGroup.count; i++) {
                
                [self.collectionViewModelGroup[i] removeObjectAtIndex:index];
            }
            self.colorNumberLabel.text = [NSString stringWithFormat:@"%ld",[self.collectionViewModelGroup[0] count]];
            [self changeBtn:self.selectBtnTag];
        } else {
            
            [self.changeModel.colors removeObjectAtIndex:[self.collectionViewModels indexOfObject:self.currentSelectModel]];
            [self.collectionViewModels removeObject:self.currentSelectModel];
            [self changeBtn:self.selectBtnTag];
            
            
            
            self.colorNumberLabel.text = [NSString stringWithFormat:@"%ld",self.changeModel.colors.count];
        }
    }
    self.currentSelectModel.isSelect = NO;
    self.currentSelectModel = nil;
    [self.collectionView reloadData];

}

// 减少Btn
- (IBAction)subtractionBtnClick:(UIButton *)sender {
    if([self.collectionViewModelGroup[0] count] <= 1 ) {
        
        return;
    }
    
    if (self.changeModel.colors.count <= 1 ) {
        
        return;
    }
    
    
    if(self.selectBtnTag == 1004) {
        
        for (NSInteger index = 0; index < self.collectionViewModelGroup.count; index++) {
            
            [self.collectionViewModelGroup[index] removeLastObject];
            
            
            
        }
        
        for (NSInteger index = 0; index < self.changeModel.colorsGroup.count; index++) {
            
            
            [self.changeModel.colorsGroup[index] removeLastObject];
            self.currentSelectModel.isSelect = NO;
            self.currentSelectModel  = nil;
            
        }
        
        self.colorNumberLabel.text = [NSString stringWithFormat:@"%ld",[self.collectionViewModelGroup[0] count]];
        
    } else {
        
        [self.changeModel.colors removeLastObject];
        [self.collectionViewModels removeLastObject];
        
        
        self.colorNumberLabel.text = [NSString stringWithFormat:@"%ld",(long)self.changeModel.colors.count];
        
        
        
    }
    
    self.currentSelectModel.isSelect = NO;
    self.currentSelectModel  = nil;
    [self changeBtn:self.selectBtnTag];
    [self.collectionView reloadData];
}

- (IBAction)addColorBtnClick:(UIButton *)sender {

    self.currentSelectModel.isSelect = NO;
    self.currentSelectModel = nil;
    
    ZZLightViewSettingCVCellModel*model2 = [ZZLightViewSettingCVCellModel new];
    model2.model = ZZLightViewSettingCVCellStyleSelect;
    model2.color = [UIColor redColor];
    
    if (self.selectBtnTag == 1004) {
        
        for (NSInteger i = 0; i< self.collectionViewModelGroup.count; i++) {
            
            [self.collectionViewModelGroup[i] addObject:model2];
        }
        
        for (NSInteger i = 0; i < self.changeModel.colorsGroup.count; i++) {
            
            [self.changeModel.colorsGroup[i] addObject:[ZZColorRGBA colorRGBAWithR:255.0 G:0 B:0 A:1]];
        }
        
        self.colorNumberLabel.text = [NSString stringWithFormat:@"%ld",[self.collectionViewModelGroup[self.fuGaiSelectBtnTag - 3001] count]];
        
    } else {
        
        [self.collectionViewModels addObject:model2];
        [self.changeModel.colors addObject: [ZZColorRGBA colorRGBAWithR:255.0 G:0 B:0 A:1]];
        self.colorNumberLabel.text = [NSString stringWithFormat:@"%ld",self.changeModel.colors.count];
    }
    
    
    [self.collectionView reloadData];
    [self changeBtn:self.selectBtnTag];
    
}


#pragma mark - CollectionView D & D
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (self.selectBtnTag == 1004 ) {
        
        return [self.collectionViewModelGroup[self.fuGaiSelectBtnTag - 3001] count] + 1;
    }
    return self.collectionViewModels.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ZZLightViewSettingCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kZZLightLineSettingCollectionViewCellIdentifer forIndexPath:indexPath];
    
    
    if(self.collectionViewModels.count == indexPath.row && self.selectBtnTag != 1004) {
        
        ZZLightViewSettingCVCellModel *model = [ZZLightViewSettingCVCellModel new];
        
        model.isSelect = NO;
        model.model =  ZZLightViewSettingCVCellStyleAdd;
        
        cell.model = model;
    } else {
        
        if (self.selectBtnTag == 1004 ) {
            
            NSMutableArray *mtbArr = self.collectionViewModelGroup[self.fuGaiSelectBtnTag - 3001];
            if (mtbArr.count == indexPath.row) {
                
                ZZLightViewSettingCVCellModel *model = [ZZLightViewSettingCVCellModel new];
                
                model.isSelect = NO;
                model.model =  ZZLightViewSettingCVCellStyleAdd;
                
                cell.model = model;
            } else {
                cell.model = mtbArr[indexPath.row];
            }
            
        } else {
            
            cell.model = self.collectionViewModels[indexPath.row];
        }
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.collectionViewModels.count == indexPath.row || [self.collectionViewModelGroup[self.fuGaiSelectBtnTag - 3001] count] == indexPath.row) {
        
        self.currentSelectModel.isSelect = NO;
        self.currentSelectModel = nil;
        
        if (self.selectBtnTag == 1004 ) {  // 点击加号
            
            for (NSInteger index = 0; index < self.collectionViewModelGroup.count; index++) {
                
                ZZLightViewSettingCVCellModel*model2 = [ZZLightViewSettingCVCellModel new];
                model2.model = ZZLightViewSettingCVCellStyleSelect;
                model2.color = [UIColor redColor];
                [self.collectionViewModelGroup[index] addObject:model2];
            }
            
            for (NSInteger index = 0; index < self.changeModel.colorsGroup.count; index++) {
                
                [self.changeModel.colorsGroup[index] addObject:[ZZColorRGBA colorRGBAWithR:255 G:0 B:0 A:1]];
            }
            
            self.colorNumberLabel.text = [NSString stringWithFormat:@"%ld",[self.collectionViewModelGroup[0] count]];
            [self changeBtn:self.selectBtnTag];
        } else {
            
            ZZLightViewSettingCVCellModel*model2 = [ZZLightViewSettingCVCellModel new];
            model2.model = ZZLightViewSettingCVCellStyleSelect;
            model2.color = [UIColor redColor];
            [self.collectionViewModels addObject:model2];
            
            [self.changeModel.colors addObject: [ZZColorRGBA colorRGBAWithR:255.0 G:0 B:0 A:1]];
            [self changeBtn:self.selectBtnTag];
            
        }
    } else {
        
        self.currentSelectModel.isSelect = NO;
        if (self.selectBtnTag == 1004) {
            
            ZZLightViewSettingCVCellModel *model = self.collectionViewModelGroup[self.fuGaiSelectBtnTag - 3001][indexPath.row];
            model.isSelect = YES;
            self.currentSelectModel = model;
            
        } else {
            
            
            ZZLightViewSettingCVCellModel *model = self.collectionViewModels[indexPath.row];
            model.isSelect = YES;
            self.currentSelectModel = model;
        }
    }
    [self.collectionView reloadData];
}

#pragma mark - set & get
- (void)setModel:(ZZLightLineModel *)model {

    _model = model;
    [self setChangeModelForModel:model];
}

- (void)setChangeModelForModel:(ZZLightLineModel *)model {


    ZZLightLineModel *changeModel = [ZZLightLineModel new];
    if (model.model == LightLineModelCustom) {

        changeModel.model = LightLineModelLiuXing;
    } else {

        changeModel.model = model.model;
    }

    changeModel.title = model.title;
    changeModel.isAnticlockwise = model.isAnticlockwise;
    changeModel.colorNumber = model.colorNumber;
    changeModel.tuoWeiLength = model.tuoWeiLength;
    changeModel.pinLv = model.pinLv;
    changeModel.lightValue = model.lightValue;
    changeModel.colorZuHeShu = model.colorZuHeShu;
    changeModel.imageSize = model.imageSize;
    changeModel.imagePath = model.imagePath;
    changeModel.title = model.title;
    changeModel.colorsGroup = [NSMutableArray array];
    changeModel.dicrection = model.dicrection;

    for (NSInteger index = 0; index < changeModel.colorZuHeShu; index++) {

        NSMutableArray *mtbArr = model.colorsGroup[index];
        NSMutableArray *newMtbArr = [NSMutableArray array];
        for (ZZColorRGBA *rgba in mtbArr) {

            [newMtbArr addObject:[rgba copy]];
        }
        [changeModel.colorsGroup addObject:newMtbArr];
    }

    for (NSInteger index = 0; index < changeModel.colorZuHeShu; index++) {

        NSArray *models = [ZZLightViewSettingCVCellModel modesForColors:changeModel.colorsGroup[index]];
        [self.collectionViewModelGroup addObject:[NSMutableArray arrayWithArray:models]];
    }

    self.zuheLabel.text = [NSString stringWithFormat:@"%@ %ld",NSLocalizedString(@"LIGHT_LightZuhe", nil),changeModel.colorsGroup.count];

    self.zuheSlider.value = changeModel.colorZuHeShu * 0.2;
    self.zuheLabel.text = [NSString stringWithFormat:@"%@ %ld",NSLocalizedString(@"LIGHT_LightZuhe", nil),changeModel.colorZuHeShu];

    for (NSInteger i = 0; i < 5 - changeModel.colorZuHeShu; i ++) {

        [self.selectStyleView viewWithTag:3005 - i].hidden = YES;
    }



    self.colorNumberLabel.text = [NSString stringWithFormat:@"%ld",self.changeModel.colors.count];
    
    self.nameLable.text = changeModel.title;

    int length = (int)(changeModel.tuoWeiLength * 10) % 10;
//    self.tuoweiLengthLable.text = [NSString stringWithFormat:@"当前拖动长度:%d",length];
    self.tuoWeiSlider.value = changeModel.tuoWeiLength;

    NSString *path_document = NSHomeDirectory();
    //设置一个图片的存储路径
    NSString *imagePath = [path_document stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@",changeModel.imagePath]];
    self.showImageView.image = [UIImage imageWithContentsOfFile:imagePath];

    self.changeModel = changeModel;
}

#pragma mark - set & get
- (void)setChangeModel:(ZZLightLineModel *)changeModel {

    _changeModel = changeModel;

    [self changeBtn:changeModel.model];
}

- (NSMutableArray<NSMutableArray<ZZLightViewSettingCVCellModel *> *> *)collectionViewModelGroup {
    
    if (!_collectionViewModelGroup) {
        
        _collectionViewModelGroup = [NSMutableArray array];
    }
    return _collectionViewModelGroup;
}

- (NSMutableArray<ZZLightViewSettingCVCellModel *> *)collectionViewModels {
    
    return self.collectionViewModelGroup[0];
}



@end
